import qs from 'qs'
import { moduleRoutes } from '../router'
import { treeDataTranslate } from '@/utils/index'
import $cookies from '@/utils/cookies.js'

export default {
  data () {
    /* eslint-disable */
    return {
      // 设置属性
      mixinViewModuleOptions: {
        activatedIsNeed: true, // 此页面是否在激活（进入）时，调用查询数据列表接口？
        getDataListURL: "", // 数据列表接口，API地址
        getDataListIsPage: false, // 数据列表接口，是否需要分页？
        deleteURL: "", // 删除接口，API地址
        deleteIsBatch: false, // 删除接口，是否需要批量？
        deleteIsBatchKey: "id", // 删除接口，批量状态下由那个key进行标记操作？比如：pid，uid...
        exportURL: "", // 导出接口，API地址
        getTreeDataListURL: "",
        treeType: false,
      },
      headLock: true, // 锁定表头
      tableHeight: 400, // table 高度
      tableHeightHold: 0, // table 高度 页高中不能占用的部分
      leftHeightHold: 0, // table 高度 页高中不能占用的部分
      queryHeight: 0, // 查询表单高度
      // 默认属性
      dataForm: {}, // 查询条件
      dataList: [], // 数据列表
      order: "", // 排序，asc／desc
      orderField: "", // 排序，字段
      sumFields: "", // 合计，数据字段列表
      sumData: {}, // 合计，后台计算数据
      page: 1, // 当前页码
      limit: 10, // 每页数
      total: 0, // 总条数
      pageSizes: [10, 50, 100, 500, 1000], // 分页条数设置
      dataListLoading: false, // 数据列表，loading状态
      searchShow: true,
      queryShow: false,
      dataListSelections: [], // 数据列表，多选项
      addOrUpdateVisible: false, // 新增／更新，弹窗visible状态
    };
    /* eslint-enable */
  },
  activated () {
    if (this.mixinViewModuleOptions.activatedIsNeed) {
      if (this.mixinViewModuleOptions.treeType) {
        this.getTreeDataList()
      } else {
        this.getDataList()
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      // 获取查询面板高度
      this.getQueryHeight()
      this.setTableHeight()
      this.tableHeight = this.getTableHeight(this.searchShow, this.queryHeight)
    })
  },
  watch: {
    searchShow (val) {
      if (this.headLock) {
        this.tableHeight = this.getTableHeight(val, this.queryHeight)
      }
    },
    queryShow (val) {
      this.$nextTick(() => {
        this.getQueryHeight()
        this.setTableHeight()
      })
    }
  },
  computed: {
    // tableCard高度
    tableCardHeight: function () {
      let tableHeight = 0
      var h =
        document.documentElement.clientHeight || document.body.clientHeight
      tableHeight = h - 50 - 38 - 20 - 2
      if (this.queryHeight) {
        tableHeight = tableHeight - this.queryHeight - 5
      }
      return tableHeight
    },
    // table高度
    tablebBodyHeight: function () {
      let height
      if (this.mixinViewModuleOptions.treeType) {
        height = this.tableCardHeight - 52 - 10
      } else {
        height = this.tableCardHeight - 52 - 32 - 15 - 10
      }
      if (this.tableHeightHold) {
        return height - this.tableHeightHold
      }
      return height
    },
    listLeftBodyHeight: function () {
      console.log(1)
      console.debug(this.tableCardHeight - this.tablebBodyHeight - this.queryHeight)
      let height
      height = this.tableCardHeight - (this.tableCardHeight - this.tablebBodyHeight - this.queryHeight) - this.leftHeightHold + 12
      return height
    }
  },
  methods: {
    /**
     * 查询事件
     */
    searchListEvent () {
      this.page = 1
      if (this.mixinViewModuleOptions.treeType) {
        this.getTreeDataList()
      } else {
        this.getDataList()
      }
    },
    // 获取查询面板高度
    getQueryHeight () {
      if (this.$refs.query) {
        this.queryHeight = this.$refs.query.$el.offsetHeight + 1
      } else {
        let cardQuerys = document.querySelectorAll('.aui-card-list-query')
        if (cardQuerys.length) {
          this.queryHeight = cardQuerys[0].offsetHeight + 1
        }
      }
      // console.log('queryHeight', this.queryHeight)
    },
    // 设置table高度
    setTableHeight () {
      // 设置card高度
      let cardBodys = document.querySelectorAll(
        '.aui-card-list-body > .el-card__body'
      )
      if (cardBodys.length) {
        cardBodys[0].style.minHeight = `${this.tableCardHeight}px`
      }
      let leftBodys = document.querySelectorAll(
        '.el-aside > .aui-card-list-left > .el-card__body > .body'
      )
      if (leftBodys.length) {
        leftBodys[0].style.height = `${this.listLeftBodyHeight}px`
      }
      if (this.headLock) {
        // 设置固定表头宽度
        let tableBodys = document.querySelectorAll(
          '.aui-card-list-body > .el-card__body > .aui-card-list-body-table'
        )
        if (!tableBodys.length) {
          tableBodys = document.querySelectorAll(
            '.aui-card-list-body > .el-card__body > div > .aui-card-list-body-table'
          )
        }
        if (tableBodys.length) {
          tableBodys[0].style.height = `${this.tablebBodyHeight}px`
        }
      }
    },
    // 计算高度
    getTableHeight (searchShow, queryHeight) {
      var h =
        document.documentElement.clientHeight || document.body.clientHeight
      let tableHeight = 0
      if (searchShow) {
        tableHeight = h - queryHeight - this.tableHeightHold
      } else {
        tableHeight = h - this.tableHeightHold
      }
      return tableHeight
    },
    // 排序算法
    sortChange ({ column, property, order }) {
      this.order = order
      this.orderField = column.sortBy
      if (this.mixinViewModuleOptions.treeType) {
        this.getTreeDataList()
      } else {
        this.getDataList()
      }
    },
    // 获取数据列表
    getDataList () {
      // this.$userBehavior.sendUserBehavior(this.$route.path, 0, 'getDataList', '获取列表数据--' + this.mixinViewModuleOptions.getDataListURL)
      return new Promise((resolve, reject) => {
        if (!this.mixinViewModuleOptions.getDataListURL) {
          reject(new Error('url 地址不能为空'))
          return
        }
        this.dataListLoading = true
        this.$http
          .get(this.mixinViewModuleOptions.getDataListURL, {
            params: {
              order: this.order,
              orderField: this.orderField,
              sumFields: this.sumFields,
              page: this.mixinViewModuleOptions.getDataListIsPage
                ? this.page
                : null,
              limit: this.mixinViewModuleOptions.getDataListIsPage
                ? this.limit
                : null,
              ...this.dataForm
            }
          })
          .then(({ data: res }) => {
            this.dataListLoading = false
            this.dataList = []
            if (res.code !== 0) {
              this.dataList = []
              this.total = 0
              reject(new Error(false))
              return
            }
            this.dataList = this.mixinViewModuleOptions.getDataListIsPage
              ? res.data.list
              : res.data
            this.total = this.mixinViewModuleOptions.getDataListIsPage
              ? res.data.total
              : 0
            this.sumData = this.mixinViewModuleOptions.getDataListIsPage
              ? res.data.sumData
              : {}
            if (this.total > 0 && Math.ceil(this.total / this.limit) === 1) {
              this.page = 1
            }
            resolve(this.dataList)
          })
          .catch((e) => {
            this.dataListLoading = false
            console.error(e)
            reject(new Error(false))
          })
      })
    },
    // 获取树表数据
    getTreeDataList () {
      this.dataListLoading = true
      // this.$userBehavior.sendUserBehavior(this.$route.path, 0, 'getTreeDataList', '获取列表数据--' + this.mixinViewModuleOptions.getTreeDataListURL)
      let rows = this.$refs.xTree.getTreeExpandRecords()
      this.$refs.xTree.clearTreeExpand()
      this.$http
        .get(this.mixinViewModuleOptions.getTreeDataListURL, {
          params: {
            ...this.dataForm
          }
        })
        .then(({ data: res }) => {
          this.dataListLoading = false
          if (res.code !== 0) {
            return
          }
          this.dataList = treeDataTranslate(res.data, 'id', 'pid')
          this.$xeutils.eachTree(this.dataList, (item) => {
            if (this.$xeutils.find(rows, (val) => val.id === item.id)) {
              this.$refs.xTree.toggleTreeExpansion(item)
            }
          })
        })
        .catch((err) => {
          this.dataListLoading = false
          return this.$message.error(err)
        })
    },
    // 多选
    dataListSelectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 多选
    dataListSelectionChangeHandleVex (val) {
      this.dataListSelections = val.selection
    },
    // 多选
    dataListSelectionAllChangeHandleVex (val) {
      this.dataListSelections = val.selection
    },
    // 排序
    dataListSortChangeHandle (data) {
      if (!data.order || !data.prop) {
        this.order = ''
        this.orderField = ''
        return false
      }
      this.order = data.order.replace(/ending$/, '')
      this.orderField = data.prop.replace(/([A-Z])/g, '_$1').toLowerCase()
      this.getDataList()
    },
    // 分页, 每页条数
    pageSizeChangeHandle (val) {
      this.page = 1
      this.limit = val
      this.getDataList()
    },
    // 分页, 当前页
    pageCurrentChangeHandle (val) {
      this.page = val
      this.getDataList()
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.dataForm.id = id
        this.$refs.addOrUpdate.init()
      })
      if (id) {
        this.$userBehavior.sendUserBehavior(
          this.$route.path,
          this.$route.meta.menuId,
          1,
          'edit',
          id
        )
      } else {
        this.$userBehavior.sendUserBehavior(
          this.$route.path,
          this.$route.meta.menuId,
          1,
          'add',
          ''
        )
      }
    },
    // 更新合计行
    updateFooter () {
      this.$refs.xTable.updateFooter()
    },
    // 搜索清空
    searchReset () {
      this.dataForm = this.initDataForm || {}
    },
    //
    searchShowHandle () {
      this.searchShow = !this.searchShow
    },
    // 删除
    deleteHandle (id) {
      // this.$userBehavior.sendUserBehavior(this.$route.path, 0, 'deleteHandle', '删除数据--' + this.mixinViewModuleOptions.deleteURL)
      if (
        this.mixinViewModuleOptions.deleteIsBatch &&
        !id &&
        this.dataListSelections.length <= 0
      ) {
        return this.$message({
          message: this.$t('prompt.deleteBatch'),
          type: 'warning',
          duration: 500
        })
      }
      this.$confirm(
        this.$t('prompt.info', { handle: this.$t('delete') }),
        this.$t('prompt.title'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          this.$http
            .delete(
              `${this.mixinViewModuleOptions.deleteURL}${this.mixinViewModuleOptions.deleteIsBatch ? '' : '/' + id
              }`,
              this.mixinViewModuleOptions.deleteIsBatch
                ? {
                  data: id
                    ? [id]
                    : this.dataListSelections.map(
                      (item) =>
                        item[this.mixinViewModuleOptions.deleteIsBatchKey]
                    )
                }
                : {}
            )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return
              }
              this.$message({
                message: this.$t('prompt.success'),
                type: 'success',
                duration: 500,
                onClose: () => {
                  if (this.mixinViewModuleOptions.treeType) {
                    this.getTreeDataList()
                  } else {
                    this.getDataList()
                  }
                }
              })
              if (id) {
                this.$userBehavior.sendUserBehavior(
                  this.$route.path,
                  this.$route.meta.menuId,
                  1,
                  'delete',
                  id
                )
              } else {
                this.$userBehavior.sendUserBehavior(
                  this.$route.path,
                  this.$route.meta.menuId,
                  1,
                  'deleteAll',
                  ''
                )
              }
            })
            .catch(() => { })
        })
        .catch(() => { })
    },
    // 导出
    exportHandle (isPage) {
      var params = qs.stringify({
        token: $cookies.get('token'),
        page:
          isPage && this.mixinViewModuleOptions.getDataListIsPage
            ? this.page
            : null,
        limit:
          isPage && this.mixinViewModuleOptions.getDataListIsPage
            ? this.limit
            : null,
        ...this.dataForm
      })
      window.location.href = `${window.SITE_CONFIG['apiURL']}${this.mixinViewModuleOptions.exportURL}?${params}`
    },
    /**
     *
     * @param router {name:新路由,id:业务id,oldName:当前页路由,path:打开页面的路径,title:tabTitle}
     * @param params {} 路由参数
     * @returns {*|number}
     */
    openNewTab ($router, router, params) {
      // 组装路由名称, 并判断是否已添加, 如是: 则直接跳转
      var routeName = router.name + `__` + router.id
      var route
      if (router.children && router.children.length > 0) {
        var childName = router.children[0].name
        route = window.SITE_CONFIG['dynamicRoutes'].filter(
          (item) => item.name === childName
        )[0]
        if (route) {
          return $router.push({ name: childName, params: params })
        }
      } else {
        route = window.SITE_CONFIG['dynamicRoutes'].filter(
          (item) => item.name === routeName
        )[0]
        if (route) {
          return $router.push({ name: routeName, params: params })
        }
      }

      // 否则: 添加并全局变量保存, 再跳转
      route = {
        path: router.oldName + `__` + router.id,
        component: () => import(`@/views/modules/${router.path}`),
        name: routeName,
        meta: {
          ...window.SITE_CONFIG['contentTabDefault'],
          menuId: router.menuId,
          isTab: true,
          title: '' + router.title
        },
        children: router.children
      }
      $router.addRoutes([
        {
          ...moduleRoutes,
          name: `main-dynamic__${router.name}`,
          children: [route]
        }
      ])
      window.SITE_CONFIG['dynamicRoutes'].push(route)
      if (router.children && router.children.length > 0) {
        $router.push({ name: router.children[0].name, params: params })
      } else {
        $router.push({ name: route.name, params: params })
      }
    }
  }
}
